package com.gzz.orchid.main.facade.controller.example;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.gzz.orchid.common.core.util.I18nUtil;
import com.gzz.orchid.common.webmvc.configuration.CustomParameter;
import com.gzz.orchid.common.webmvc.securityjwt.JwtUtil;
import com.gzz.orchid.common.webmvc.util.ReqUtil;
import com.gzz.orchid.main.facade.controller.pojo.RegisterRequest;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/example/jwt")
public class JwtTokenController {
    @Autowired
    private CustomParameter config;
    @Resource
    private MessageSource messageSource;


    @PostConstruct
    public void init() {
        log.error("启动这样的Application is starting。。。。");
    }


    /**
     * 获取Token
     *
     * @param username 用户名
     * @return 生成的Token
     */
    @RequestMapping("/getToken")
    public String getToken(String username) {
        System.out.println("用户名：" + config.getName());
        System.out.println("年龄：    " + config.getAge());
        System.out.println("性别：    " + config.getSex());
        System.out.println("地址：    " + config.getAddress());
        return JwtUtil.generateToken(Map.of("MHK-key", "I am Ricky", "username", "用户名"));
    }

    /**
     * 测试验证
     *
     * @param token
     * @return
     */
    @RequestMapping("/verifyToken")
    public String verifyToken(String token) {
        try {
            System.out.println("--Header-----------------------------------------");
            System.out.println(JWT.decode(token).getHeader());
            System.out.println("--Payload-----------------------------------------");
            System.out.println(JWT.decode(token).getPayload());
            System.out.println("--Subject-----------------------------------------");
            System.out.println(JWT.decode(token).getSubject());
            System.out.println("--Signature-----------------------------------------");
            System.out.println(JWT.decode(token).getSignature());
            System.out.println("--ExpiresAt-----------------------------------------");
            System.out.println(JWT.decode(token).getExpiresAt());
            System.out.println("--Algorithm-----------------------------------------");
            System.out.println(JWT.decode(token).getAlgorithm());
            System.out.println("--ID-----------------------------------------");
            System.out.println(JWT.decode(token).getId());
            System.out.println("--Token-----------------------------------------");
            System.out.println(JWT.decode(token).getToken());
            System.out.println("--KeyId-----------------------------------------");
            System.out.println(JWT.decode(token).getKeyId());
            System.out.println("--Issuer-----------------------------------------");
            System.out.println(JWT.decode(token).getIssuer());
            System.out.println("--NotBefore-----------------------------------------");
            System.out.println(JWT.decode(token).getNotBefore());
            System.out.println("--Type-----------------------------------------");
            System.out.println(JWT.decode(token).getType());
            System.out.println("--ContentType-----------------------------------------");
            System.out.println(JWT.decode(token).getContentType());

        } catch (Exception ex) {
            log.error("Token无法通过验证! " + ex.getMessage());
        }
        DecodedJWT decodedJWT = JwtUtil.parseJWT(token);
        decodedJWT.getClaims().forEach((k, v) -> {
            log.info("key: {}, value:{}", k, v.asString());
        });
        //
        //        return  JwtUtil.validateToken(token) ? "验证成功" : "验证失败";
        log.info("Token: {}", token);
        return Objects.isNull(token) ? "验证失败" + Instant.now() : "验证成功" + Instant.now();
    }

    /**
     * 测试验证
     *
     * @param req
     * @return
     */
    @RequestMapping("/register")
    public String register(@Valid RegisterRequest req) {
        log.info("用户名：{}", req.getUsername());
        log.info("密码：{}", req.getPassword());
        return "成功";
    }

    /**
     * \
     * 获取所有message
     *
     * @return
     */
    @RequestMapping("/getAllMessages")
    public Map<String, String> getAllMessages() {
        System.out.println(ReqUtil.getUserAgent());
        System.out.println(ReqUtil.getTerminal());
        Locale locale = Locale.getDefault();
        System.out.println(locale);
        System.out.println("===获取访问终端的语言==================");
        Locale currentLocale = LocaleContextHolder.getLocale();
        System.out.println(currentLocale);

        String msg2 = I18nUtil.message("welcome.message");
        String defmsg = I18nUtil.message("password.incorrect", "张家辉是张学友的兄弟");
        String msg = I18nUtil.message("login.success", "张家常", "2022-01-01");


        //存放所有message
        //Map<String, String> messages = new HashMap<>();

        //        ResourceBundleMessageSource bundleMessageSource = (ResourceBundleMessageSource) messageSource;
        //        String[] basenames = bundleMessageSource.getBasenameSet().toArray(new String[0]);
        //        System.out.println(basenames);
        //        for (String basename : basenames) {
        //            //从缓存中获取资源文件
        //            ResourceBundle resourceBundle = ResourceBundle.getBundle(basename, locale);
        //            //获取资源文件的所有code
        //            Set<String> keys = resourceBundle.keySet();
        //
        //            for (String key : keys) {
        //                //根据code获取对应的message
        //                String message = messageSource.getMessage(key, null, locale);
        //                messages.put(key, message);
        //            }
        //        }
        return Map.of("message", msg2, "text", msg, "default", defmsg);
    }
}
